package leetcode.datastructure.array;

import java.util.Arrays;

/**
 * 乘法太多浪费计算时间
 */
public class Program274HIndex {

    public Program274HIndex() {
    }

    public int hIndex(int[] citations) {
//        return exec(citations);
        return office(citations);
    }

    public int exec(int[] citations) {
        int length = citations.length;
        if (length < 1) {
            return 0;
        }
        if (length == 1) {
            return citations[0] == 0 ? 0 : 1;
        }
        int[] tmp = new int[citations.length];
        for (int i = 0; i <length; i++) {
            for (int j = 0; j < Math.min(length, citations[i]); j++) {
                tmp[j]++;
            }
        }

        for (int i = length - 1; i >= 0; i-- ) {
            if (tmp[i] >= i + 1) {
                return i +1;
            }
        }
        return 0;
    }

    public int office(int[] citations) {
        // 下标后边的值，有多少
        Arrays.sort(citations); // 排序时间的时间复杂O(nlogn) 空间复杂度O(logn)
        int h = 0, i = citations.length - 1;
        while (i >= 0 && citations[i] > h) {
            h++;
            i--;
        }
        return h;
    }

    public static void main(String[] args) {
        Program274HIndex myStack = new Program274HIndex();
        int[] prices = {3,0,6,1,5};
        System.out.println(myStack.hIndex(prices));
        int[] prices2 = {1,3,1};
        System.out.println(myStack.hIndex(prices2));
//        int[] prices3 = {2,0,0};
//        System.out.println(myStack.hIndex(prices3));
    }
}
